package com.cl.base.handler;

import com.cl.base.handler.annotation.NotControllerResponseAdvice;
import com.cl.base.util.JsonUtil;
import com.cl.base.util.ResultVo;
import lombok.RequiredArgsConstructor;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@RestControllerAdvice(basePackages = {"com.cl.base"})
@RequiredArgsConstructor
public class ControllerResponseAdvice implements ResponseBodyAdvice<Object> {
    private final JsonUtil jsonUtil;

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        // response是ResultVo类型，或者注释了NotControllerResponseAdvice都不进行包装
        return !(returnType.getParameterType().isAssignableFrom(ResultVo.class) || returnType.hasMethodAnnotation(NotControllerResponseAdvice.class));
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        // String类型不能直接包装
        if (returnType.getGenericParameterType().equals(String.class)) {
            // 将数据包装在ResultVo里后转换为json串进行返回
            return jsonUtil.toString(ResultVo.ok(body));
        }
        // 否则直接包装成ResultVo返回
        return ResultVo.ok(body);
    }
}


